import React, {useState} from "react";
import {apiModifyUserAvatar} from "@/common/apis/user";
import {message} from "antd";

function AvatarEditButton() {

  const handleClick = () => {
    const uploadInput: any = document.getElementById('myhome-conceal-file-upload')
    uploadInput.click()
  }

  const [fileData, setFileData] = useState<any>(null)
  const [disable, setDisable] = useState(false)

  const fileReady = (e: any) => {
    console.log('[已选择文件]', e.target.files);
    setFileData(e.target.files[0])
  }

  const handleUpload = async () => {
    setDisable(true)
    const formData = new FormData()
    formData.append('avatar', fileData)
    const res = await apiModifyUserAvatar(formData)
    if (res.code === 0) {
      message.success("修改成功")
    }
  }

  return (
    <>
      {
        !fileData ?
          <button className='button' onClick={handleClick}>
            修改头像
            <input
              type='file'
              accept='image/*'
              style={{display: 'none'}}
              id='myhome-conceal-file-upload'
              onClick={e => {
                e.stopPropagation()
              }}
              onChange={e => {
                fileReady(e)
              }}
            />
          </button>
          :
          <button className='button' onClick={handleUpload} disabled={disable}>
            {'已选择文件 点击上传'}
          </button>
      }
    </>
  )
}

export default AvatarEditButton
